package com.cn.jinl.service;

import com.cn.jinl.api.IProductStorageService;
import com.cn.jinl.dao.BoxManageMapper;
import com.cn.jinl.dao.ProductStorageMapper;
import com.cn.jinl.dao.ProductStorageRelateMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.GenerateUUID;
import com.cn.jinl.utils.QueryForm;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ProductStorageServiceImpl implements IProductStorageService {

    @Autowired
    private ProductStorageMapper productStorageMapper;

    @Autowired
    private ProductStorageRelateMapper productStorageRelateMapper;

    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    private BoxManageMapper boxManageMapper;


    @Override
    public List<ProductStorage> getProductStorageList(QueryForm queryForm) throws Exception {
        int count = productStorageMapper.selectProductStorageListCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<ProductStorage> productStorages = productStorageMapper.selectProductStorageList(queryForm);
        productStorages.get(0).setCount(count);
        return productStorages;
    }

    @Override
    public List<ProductStorageMXVo> getProductStorageMXList(QueryForm queryForm) throws Exception {
       //默认查询近三个月
        if (queryForm.getStartTime() == null || queryForm.getStartTime().isEmpty()) {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            // 设置endTime为当前时间
            queryForm.setEndTime(sdf1.format(new Date()));
            // 设置startTime为1个月前
            calendar.add(Calendar.MONTH, -1);
            queryForm.setStartTime(sdf.format(calendar.getTime()));
        }
        int count = productStorageMapper.selectProductStorageMXListCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<ProductStorageMXVo> productStorages = productStorageMapper.selectProductStorageMXList(queryForm);
        productStorages.get(0).setCount(count);
        return productStorages;
    }

    @Override
    public ProductStorage getProductStorageById(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return new ProductStorage();
        }

        ProductStorageExample example = new ProductStorageExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andIdEqualTo(id);
        List<ProductStorage> productStorages = productStorageMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(productStorages)){
            return new ProductStorage();
        }
        ProductStorage exist = productStorages.get(0);
        List<ProductStorageVo> productStorageVos = productStorageRelateMapper.selectProductStorageRelateById(id);
        Map<String,ProductStorageVo> voMaps = Maps.newHashMap();
        for(ProductStorageVo vo:productStorageVos){
            if(voMaps.containsKey(vo.getPlanCode()+","+vo.getGradeValue())){
                int count = voMaps.get(vo.getPlanCode()+","+vo.getGradeValue()).getStorageCount()+1;
                voMaps.get(vo.getPlanCode()+","+vo.getGradeValue()).setStorageCount(count);
            }else{
                vo.setStorageCount(1);
                voMaps.put(vo.getPlanCode()+","+vo.getGradeValue(),vo);
            }
        }
        List<ProductStorageVo> newList = Lists.newArrayList();
        for(String key:voMaps.keySet()){
            newList.add(voMaps.get(key));
        }
        exist.setProductStorageVos(newList);
        return exist;
    }

    @Override
    public ProductStorage getOnlyProductStorageById(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return null;
        }

        ProductStorageExample example = new ProductStorageExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andIdEqualTo(id);
        List<ProductStorage> productStorages = productStorageMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(productStorages)){
            return null;
        }
        return  productStorages.get(0);
    }

    @Override
    public String addProductStorage(ProductStorage productStorage) throws Exception {
        int count = productStorageMapper.insertSelective(productStorage);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateProductStorage(ProductStorage productStorage) throws Exception {
        ProductStorageExample example = new ProductStorageExample();
        example.createCriteria().andIdEqualTo(productStorage.getId());
        int count = productStorageMapper.updateByExampleSelective(productStorage,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateTestBatchProductStorage() throws Exception {
        FileInputStream file = new FileInputStream("E:\\program\\rf\\plans.xlsx");
        Workbook workbook = WorkbookFactory.create(file);
        Sheet sheet = workbook.getSheetAt(0);
        int lastRaw = 1155;
        String storageId = CommonUtil.generateRandomNum("storage_");
        String yearMoth = generateUUID.getYearMoth();
        String key = yearMoth+"storage";
        int num = generateUUID.getNumberFlag(key);
        String code = "RK"+yearMoth+generateUUID.getThreeNumStr(num);
        ProductStorage productStorage = new ProductStorage();
        productStorage.setId(storageId);
        productStorage.setStorageCode(code);
        productStorage.setStorageType("1");
        productStorage.setStorageStatus("1");
        productStorage.setStorageUserName("admin");
        productStorage.setStorageUserId("1");

        Set<String> gradeSet = Sets.newHashSet();
        int boxCodeNum = 1;
        int totalCount = 0;
        for (int i = 1; i < lastRaw; i++) {
            Row row = sheet.getRow(i);
            ProductStorageRelate relate = new ProductStorageRelate();
            relate.setStorageId(storageId);
            for(int j = 0 ;j < 5;j++){
                Cell cell = row.getCell(j);
                if (cell == null) {
                    continue;
                }
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String cellContent = cell.getStringCellValue();
                if(j == 0 && StringUtils.isEmpty(cellContent)){
                    break;
                }
               if(j == 1){
                    relate.setItemTypeId(cellContent);
                }else if( j== 2){
                    relate.setGradeValue(cellContent);
                }else if( j== 4){
                    relate.setStorageInCount(Integer.parseInt(cellContent));
                }
            }
            gradeSet.add(relate.getGradeValue());
            relate.setDutyDay("2024-04-25");
            relate.setWhiteDay("1");
            relate.setUserName("admin");
            relate.setTaskId("1");
            int storageCount = relate.getStorageInCount();
            totalCount+=storageCount;
            for(int j =0;j < storageCount;j++){
                String boxCode = "";
                if(boxCodeNum < 10){
                    boxCode = "2400000"+boxCodeNum;
                }else if(boxCodeNum < 100){
                    boxCode = "240000"+boxCodeNum;
                }else if(boxCodeNum < 1000){
                    boxCode = "24000"+boxCodeNum;
                }else {
                    boxCode = "2400"+boxCodeNum;
                }
                relate.setBoxCode(boxCode);
                productStorageRelateMapper.insertSelective(relate);
                BoxManageExample example = new BoxManageExample();
                example.createCriteria().andBoxCodeEqualTo(boxCode);
                BoxManage update = new BoxManage();
                update.setPrintUserName("admin");
                update.setPrintTime("2024-04-25");
                boxManageMapper.updateByExampleSelective(update,example);
                ++boxCodeNum;
            }

        }
        productStorage.setStorageGradeCount(gradeSet.size());
        productStorage.setStorageCount(totalCount);
        String resp = this.addProductStorage(productStorage);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception("更新异常！");
        }
        return null;
    }
}
